package com.sqly.doc.menu.grjbxx;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cazaea.sweetalert.SweetAlertDialog;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.sqly.doc.R;
import com.sqly.doc.adapter.CommonAdapter;
import com.sqly.doc.adapter.ViewHolder;
import com.sqly.doc.base.MyBaseActivity;
import com.sqly.doc.ble.xyy.DeviceActivity;
import com.sqly.doc.pojo.BleMeasureRecord;
import com.sqly.doc.pojo.RetMsg;
import com.sqly.doc.util.DateConvert;
import com.sqly.doc.util.HttpUrl;
import com.sqly.doc.util.MyToastUtil;
import com.sqly.doc.util.NetWorkUtils;
import com.sqly.doc.util.SharedPreferencesUtils;
import com.sqly.doc.util.SweetAlertDialogUtil;
import com.sqly.doc.util.UserClient;
import com.sqly.doc.view.StringUtils;
import com.sqly.doc.view.XListView;
import com.zyao89.view.zloading.ZLoadingDialog;
import com.zyao89.view.zloading.Z_TYPE;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 * 个人基本信息复核列表
 * Created by Administrator on 2017-11-14.
 */

public class measre_record_list extends MyBaseActivity {


    XListView listView;
    //标题
    TextView title, uname;
    LinearLayout back;
    ZLoadingDialog dialog;//加载动画
    Context con = measre_record_list.this;
    private int pageNum1 = 1;// 无关键字页数
    List<BleMeasureRecord> BleMeasureRecordlist;
    String url = "";//请求的路径
    private EditText key;
    @Override
    protected void initUI() {
        setContentView(R.layout.measure_record_list);
        title = (TextView) findViewById(R.id.title);
        uname = (TextView) findViewById(R.id.uname);
        url = HttpUrl.GetBleMRecordList;

        final String category = getIntent().getStringExtra("category");
        String titleStr = "";
        if(null != category && "1".equals(category)){
            titleStr = "血糖测量记录";
        }else {
            titleStr = "血压测量记录";
        }
        title.setText(titleStr);
        key=(EditText)findViewById(R.id.key);
        key.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                getDataList();
            }
        });
        uname.setText("新增");
        uname.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(null != category && "1".equals(category)){
                    String xtyval = (String) SharedPreferencesUtils.getParam(con, "xtyval", "");
                    if(null == xtyval || "".equals(xtyval)) {
                        SweetAlertDialogUtil.WarningDialog(con, "提示", "请先绑定蓝牙血糖仪设备");
                    }else {
                        startActivity(new Intent(con, measure_xt_add.class).putExtra("type", "add"));
                    }
                }else {
//                    startActivity(new Intent(con, DeviceActivity.class).putExtra("type", "add"));
                    String xyjval = (String) SharedPreferencesUtils.getParam(con, "xyjval", "");
                    if(null == xyjval || "".equals(xyjval)) {
                        SweetAlertDialogUtil.WarningDialog(con, "提示", "请先绑定蓝牙血压计设备");
                    }else {
                        startActivity(new Intent(con, measure_xy_new_add.class).putExtra("type", "add"));
                    }
                }
            }
        });
        back = (LinearLayout) findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        listView = (XListView) findViewById(R.id.listView);
        listView.setPullLoadEnable(true);
        dialog = new ZLoadingDialog(con);
        dialog.setLoadingBuilder(Z_TYPE.DOUBLE_CIRCLE)//设置类型
                .setLoadingColor(Color.parseColor("#1C86EE"))//颜色
                .setHintText("Loading...")
                .setHintTextSize(16) // 设置字体大小 dp
                .setHintTextColor(Color.parseColor("#1C86EE"));  // 设置字体颜色
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                new SweetAlertDialog(con, SweetAlertDialog.ERROR_TYPE)
                        .setTitleText("提示")
                        .setContentText("确定删除该条测量记录?")
                        .setConfirmText("确定")
                        .setCancelText("取消")
                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                sweetAlertDialog.dismiss();
                                RequestParams ps = new RequestParams();
                                ps.add("token", SharedPreferencesUtils.getParam(con, "token", "").toString());
                                ps.add("type", "2");
                                ps.add("id", BleMeasureRecordlist.get(position - 1).getRid());
                                UserClient.get(HttpUrl.DelBleMRecord, ps, new AsyncHttpResponseHandler() {
                                    @Override
                                    public void onSuccess(int statusCode, Header[] headers, byte[] response) {
                                        String content = new String(response);
                                        RetMsg ret = JSON.parseObject(content, RetMsg.class);
                                        if (ret.getCode().equals("200")) {
                                            BleMeasureRecord obj = (BleMeasureRecord)BleMeasureRecordlist.get(position - 1);
                                            MyToastUtil.ShowToast(con, "成功");
                                        }else{
                                            MyToastUtil.ShowToast(con, ret.getInfo());
                                        }
                                        getDataList();
                                    }

                                    @Override
                                    public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

                                    }
                                });
                            }
                        })
                        .show();
            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (NetWorkUtils.isNetworkConnected(con)) {//联网状态
            getDataList();
        }
    }

    @Override
    protected void initListener() {

    }

    public void getDataList() {
        final String category = getIntent().getStringExtra("category");
        RequestParams ps = new RequestParams();
        ps.add("token", SharedPreferencesUtils.getParam(con, "token", "").toString());
        ps.add("type", "2");
        ps.add("category", category);
        ps.add("page", pageNum1 + "");
        if(!StringUtils.isEmpty(key.getText().toString()))
            ps.add("name",key.getText().toString());
      /*  ps.add("XINGMING",SharedPreferencesUtils.getParam(con,"uname","").toString());*/
        UserClient.get(url, ps, new AsyncHttpResponseHandler() {
            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {

                MyToastUtil.ShowToast(con, "请求失败");
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] response) {
                String content = new String(response);
                dialog.dismiss();
                RetMsg ret = JSON.parseObject(content, RetMsg.class);
                if (ret.getCode().equals("200")) {
                    List<BleMeasureRecord> ll = JSON.parseArray(ret.getList(), BleMeasureRecord.class);
                    if (pageNum1 == 1) {
                        BleMeasureRecordlist = new ArrayList<BleMeasureRecord>();
                    }
                    JSONArray js = JSON.parseArray(ret.getList());
                    for (int i = 0; i < js.size(); i++) {
                        JSONObject j = js.getJSONObject(i);
                        ll.get(i).setRid(j.getString("id"));
                    }
                    for (int i = 0; i < ll.size(); i++) {
                        BleMeasureRecordlist.add(ll.get(i));
                    }
                    listView.stopRefresh();
                    listView.stopLoadMore();
                    listView.setRefreshTime("刚刚");
                    listView.setXListViewListener(new XListView.IXListViewListener() {
                        @Override
                        public void onRefresh() {
                            pageNum1 = 1;
                            getDataList();
                        }

                        @Override
                        public void onLoadMore() {
                            pageNum1 = pageNum1 + 1;
                            getDataList();
                        }
                    });
                    listView.setAdapter(new CommonAdapter<BleMeasureRecord>(con, BleMeasureRecordlist, R.layout.measure_record_list_item) {
                        @Override
                        public void convert(ViewHolder helper, BleMeasureRecord item) {
                            helper.setText(R.id.jmxm, "" + item.getJmname()+"("+item.getJmsfzh()+")");
                            if(null != category && "1".equals(category)){
                                helper.setText(R.id.measureval, item.getVal1()+"mmol/L");
                            }else{
                                helper.setText(R.id.measureval, item.getVal1()+"/"+item.getVal2());
                            }
                            helper.setText(R.id.measuresj, "时间："+DateConvert.dateToString(DateConvert.toDate(item.getTbtime(), DateConvert.YMDHMS), DateConvert.YMDHMS)+"    ");
                        }
                    });
                    listView.setSelection(BleMeasureRecordlist.size() - ll.size());
                }
            }
        });
    }
}
